//
//  HACAnimator.m
//  HStockCharts
//
//  Created by Hotacool on 2018/1/2.
//

#import "HACAnimator.h"

#define AnimatorPhaseFull 1.0
@implementation HACAnimator {
    CADisplayLink *_displayLink;
    BOOL _enableX;
    BOOL _enableY;
    NSTimeInterval _startTime;
}

- (void)dealloc {
    [self stopAnimation];//未自动释放
}

- (instancetype)init {
    if ([super init]) {
        _phaseX = AnimatorPhaseFull;
        _phaseY = AnimatorPhaseFull;
        _duraton = 0;
        _enableX = NO;
        _enableY = NO;
    }
    return self;
}

- (void)stopAnimation {
    if (_displayLink) {
        [_displayLink invalidate];
        _displayLink = nil;
    }
    _phaseX = AnimatorPhaseFull;
    _phaseY = AnimatorPhaseFull;
}

- (void)animateXWithDuration:(NSTimeInterval)duration {
    if (duration > 0) {
        _duraton = duration;
        _enableX = YES;
        [self startAnimate];
    }
}

- (void)startAnimate {
    [self stopAnimation];
    _startTime = CACurrentMediaTime();
    if (_enableX || _enableY) {
        _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(animationLoop)];
        [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    }
}

- (void)animationLoop {
    NSTimeInterval currentTime = CACurrentMediaTime();
    if (currentTime - _startTime >= _duraton) {
        [self stopAnimation];
        if (_delegate && [_delegate respondsToSelector:@selector(animatorStopped:)]) {
            [_delegate animatorStopped:self];
        }
    } else {
        [self updateAnimationPhases:currentTime];
        if (_delegate && [_delegate respondsToSelector:@selector(animatorUpdated:)]) {
            [_delegate animatorUpdated:self];
        }
    }
}

- (void)updateAnimationPhases:(NSTimeInterval)currentTime {
    NSTimeInterval elapsedTime = currentTime - _startTime;
    if (elapsedTime > _duraton) {
        elapsedTime = _duraton;
    }
    double phase = (double)elapsedTime / _duraton;
    if (_enableX) {
        _phaseX = phase;
    }
    if (_enableY) {
        _phaseY = phase;
    }
}
@end
